# 静态化首页工具模块
from apps.contents.models import GoodsChannel, ContentCategory
from django.template import loader
import os
from meiduo_mall.settings.dev import BASE_DIR


def generate_static_index_html():
    # 测试定时任务
    # import time
    # print(time.ctime())

    """生成静态首页的工具方法"""
    # 1.生成静态化文件的方法
    # 商品分类字典容器
    categories = {}
    # 查询所有的37个频道(一级分类)
    # GoodsChannel.objects.all().order_by('sequence')
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 遍历所有频道,取出每一个频道
    for channel in channels:
        # 通过频道数据关联的组取出对应的组号
        group_id = channel.group.id
        # 将group_id作为categories字段的key
        if group_id not in categories:  # 避免重复分组
            categories[group_id] = {'channels': [], 'sub_cats': []}

        # 获取当前频道的一级分类(一个频道对应一个一级分类)
        cat1 = channel.category
        # 添加每组中对应的频道数据
        categories[group_id]['channels'].append({
            "id": channel.id,
            "name": cat1.name,
            "url": channel.url,
        })

        # 添加每组中的二级和三级分类
        # 通过一级分类找到所有的二级分类
        for cat2 in cat1.subs.all():
            # 使用二级分类查询三级分类
            sub_cats = []
            for cat3 in cat2.subs.all():
                sub_cats.append({
                    "id": cat3.id,
                    "name": cat3.name,
                })
            categories[group_id]['sub_cats'].append({
                "id": cat2.id,
                "name": cat2.name,
                "sub_cats": sub_cats,
            })
    # 查询所有首页广告数据
    contents = {}
    # 查询官高所有类别,遍历出每一种广告
    content_categories = ContentCategory.objects.all()
    for content_cat in content_categories:
        # 遍历取出每种广告内容
        contents[content_cat.key] = content_cat.content_set.filter(status=True).order_by('sequence')

    # 2. 构造渲染html的上下文字典
    context = {
        "categories": categories,
        "contents": contents,
    }

    # 渲染页面数据
    # 获取文件目录templates中的index.html
    template = loader.get_template('indexes.html')
    # 使用上下文字典context的数据去渲染index.html
    index_html_str = template.render(context)
    # 将渲染好的HTML字符串保存到静态HTML文件中
    file_path = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'front_end_pc/indexes.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(index_html_str)